package br.fbv.compreja.activity.login;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Button;
import br.fbv.compreja.R;
import br.fbv.compreja.activity.base.BaseActivity;
import br.fbv.compreja.activity.base.BuzzException;
import br.fbv.compreja.activity.base.Command;
import br.fbv.compreja.activity.home.HomeActivity;
import br.fbv.compreja.negocio.infra.LoginConttroler;

public class LoginActivity extends BaseActivity {
	private ProgressDialog pd;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		try {
			ApplicationInfo info = getPackageManager().getApplicationInfo(
					"com.google.zxing.client", 0);
			// -- application exists
		} catch (PackageManager.NameNotFoundException e) {
			tratarExcecao(new BuzzException("É Preciso instalar a App BarCode."));
		}

		setContentView(R.layout.login);
		Button btLogin = (Button) findViewById(R.id.bt_logar);
		Command command = criarLoginComand();
		btLogin.setOnClickListener(goToActivity(this, HomeActivity.class, true,
				command));
	}

	private Command criarLoginComand() {
		Command command = new Command() {
			@Override
			public void execute() throws BuzzException {
				String userName = getStringValue(R.id.field_user);
				String psw = getStringValue(R.id.field_password);
				boolean remember = getBooleanValue(R.id.check_box_logging_automatico);
				LoginConttroler.getIntance().doLogin(LoginActivity.this,
						userName, psw, remember);
			}
		};
		return command;
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (LoginConttroler.getIntance().logarAutomaticoAtivado(this)) {
			Intent intent = new Intent(this, HomeActivity.class);
			startActivity(intent);
			finish();
		}
	}
}